package com.wulis.common.utils;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author WuliBao
 */
public class PageUtil {

    /**
     * 将IPage<S>转换为IPage<T>
     * 
     * @param sourcePage 源分页对象
     * @param targetClass 目标对象类型
     * @param <S> 源对象类型
     * @param <T> 目标对象类型
     * @return 转换后的分页对象
     */
    public static <S, T> IPage<T> convert(IPage<S> sourcePage, Class<T> targetClass) {
        // 转换列表数据
        List<T> targetList = sourcePage.getRecords().stream().map(source -> {
            try {
                T target = targetClass.getDeclaredConstructor().newInstance();
                BeanUtils.copyProperties(source, target);
                return target;
            } catch (Exception e) {
                throw new RuntimeException("对象转换失败", e);
            }
        }).collect(Collectors.toList());

        // 构建新分页对象
        IPage<T> targetPage = new Page<>();
        targetPage.setTotal(sourcePage.getTotal());
        targetPage.setSize(sourcePage.getSize());
        targetPage.setCurrent(sourcePage.getCurrent());
        targetPage.setRecords(targetList);
        return targetPage;
    }

    /**
     * 自定义转换逻辑的IPage转换
     * 
     * @param sourcePage 源分页对象
     * @param mapper 自定义转换函数
     * @param <S> 源对象类型
     * @param <T> 目标对象类型
     * @return 转换后的分页对象
     */
    public static <S, T> IPage<T> convert(IPage<S> sourcePage, Function<S, T> mapper) {
        List<T> targetList = sourcePage.getRecords().stream().map(mapper).collect(Collectors.toList());
        IPage<T> targetPage = new Page<>();
        targetPage.setRecords(targetList);
        targetPage.setTotal(sourcePage.getTotal());
        targetPage.setSize(sourcePage.getSize());
        targetPage.setCurrent(sourcePage.getCurrent());
        return targetPage;
    }
}
